package com.jqb.dom;

import java.io.File;
import java.io.IOException;
import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.XMLOutputter;
import org.junit.Test;

public class Jdom {
	@Test
	public void testJdom() throws IOException, Exception {
		jdomCreate();
		jdomParse();
	}

	public static void jdomParse() throws JDOMException, IOException {
		/*--->parsing<---*/
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(new File("src/test/resources/users.xml"));
		Element users = doc.getRootElement();
		List<Element> userList = users.getChildren("user");
		for(Element user:userList){
			System.out.print("id="+user.getAttributeValue("id"));
			System.out.println(" name="+user.getChild("name").getText());
		}
	}

	public static void jdomCreate() throws IOException {
		/*--->create<---*/
		/*创建节点*/
		Document doc = new Document();
		Element users = new Element("users");
		Element user = new Element("user");
		Element name = new Element("name");
		Attribute id = new Attribute("id", "1000");
		/*拼接节点*/
		users.addContent(user);
		user.addContent(name);
		user.setAttribute(id);
		name.setText("admin1000");
		doc.addContent(users);
		/*输出*/
		XMLOutputter out = new XMLOutputter();
		out.setFormat(out.getFormat().setEncoding("utf-8"));
		out.output(doc, System.out);
	}
}
